package com.graduation.lastproject.util.export;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class exportUtil {

    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, Map<String,Object> map, String startTime, String endTime){
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        //创建单元格样式
        HSSFCellStyle style1 = wb.createCellStyle();
        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        //创建字体样式
        HSSFFont fontTitle = createFontStyle(wb, HSSFColor.BLACK.index, HSSFFont.BOLDWEIGHT_BOLD,16);// 加粗
        style1.setFont(fontTitle);
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row0 = sheet.createRow(0);
        sheet.addMergedRegion(new CellRangeAddress(
                0, //开始行
                0, //结束行
                0, //开始列
                title.length - 1//结束列
        ));
        HSSFCell cell = row0.createCell(0);
        cell.setCellValue(sheetName);
        cell.setCellStyle(style1);

        HSSFRow row1 = sheet.createRow(1);
        HSSFCell cell1 =  row1.createCell(0);
        if("".equals(startTime) && "".equals(endTime)){
            cell1.setCellValue("统计月份：");
        }else{
            cell1.setCellValue("统计月份："+startTime);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        row1.createCell(title.length - 1).setCellValue("制表时间："+format.format(new Date()));

        HSSFRow row2 = sheet.createRow(2);   // ??
        HSSFCell cell2 = null;
        for (int i = 0; i < title.length; i++) {
            cell2 = row2.createCell(i);
            cell2.setCellValue(title[i]);
            cell2.setCellStyle(style1);
            sheet.setColumnWidth(i, 150 * 60);
        }
        String[] assetCodeArr=(String[]) map.get("hotelNameArr");
        String[] assetNameArr = (String[]) map.get("hotelPriceArr");
        String[] hotelZfbArr = (String[]) map.get("hotelZfbArr");
        HSSFRow row = sheet.createRow(3);
        for (int i = 0; i < assetNameArr.length; i++) {
            row = sheet.createRow(i + 3);
            row.createCell(0).setCellValue(assetCodeArr[i]);
            row.createCell(1).setCellValue(assetNameArr[i]);
            row.createCell(2).setCellValue(hotelZfbArr[i]);
        }
        return wb;
    }

    private static HSSFFont createFontStyle(HSSFWorkbook wb, short color, short boldweight,int fontSize) {
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) fontSize);// 字号
        font.setColor(color);
        font.setBoldweight(boldweight);
        return font;
    }

}
